class RegistrationsController < Devise::RegistrationsController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
  prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy]
  include Devise::Controllers::InternalHelpers

  def create
    build_resource

    code = resource.default_currency_code
    currency = code && Currency.find_by_code(code.upcase)
    resource.default_currency_code = currency.nil? ? "USD" : currency.code

    if resource.save
      if resource.active?
        set_flash_message :notice, :signed_up
        render :json => success(resource)
      else
        set_flash_message :notice, :inactive_signed_up, :reason => resource.inactive_message.to_s
        expire_session_data_after_sign_in!
        redirect_to after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords(resource)
      render :json => {:errorCode => 1010, # TODO
                       :errorDescription => resource.errors.as_json}.as_json
    end

    session[:omniauth] = nil unless @user.new_record?
  end

  def success(resource)
    if resource.nil?
      {
          :success => true,
          :redirect => stored_location_for(scope) || after_sign_in_path_for(resource)
      }
    else
      {
          success: true,
          email: resource.email,
          default_currency: resource.default_currency_code,
          default_wallet: "@#{resource.default_wallet.name}"
      }
    end
  end

  private

  def build_resource(*args)
    super
    if session[:omniauth]
      @user.apply_omniauth(session[:omniauth])
      @user.valid?
    end
  end
end